package com.tz;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * spring框架配置信息类
 * Created by Administrator on 2016/8/5.
 */
@Configuration
@ComponentScan //扫描的包，默认是当前包及子目录
@EnableAspectJAutoProxy //开启aop
@EnableTransactionManagement //开启声明式事务
public class AppConfig {
    //数据源
    @Bean
    public DataSource dataSource(){
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("org.h2.Driver");
        bds.setUrl("jdbc:h2:tcp://localhost/~/test");
        bds.setUsername("sa");
        bds.setPassword("");
        return bds;
    }

    //session工厂
    @Bean
    public LocalSessionFactoryBean lsfb(){
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        lsfb.setDataSource(dataSource());
        Properties props = new Properties();
        props.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
        props.setProperty("hibernate.show_sql","true");
        lsfb.setHibernateProperties(props);
        lsfb.setPackagesToScan("com.tz.entity");
        return lsfb;
    }

    //事务管理器
    @Bean
    public HibernateTransactionManager htm(){
        HibernateTransactionManager htm = new HibernateTransactionManager();
        htm.setSessionFactory(lsfb().getObject());
        return htm;
    }
}
